package com.wxx.web.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 缓存工具类
 *
 * @author <a href="https://gitee.com/you4189/you-generator">you</a>
 * @from <a href="https://gitee.com/you4189/you-generator">gitee</a>
 */
@Component
public class CacheManager {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    Cache<String, Object> localCache = Caffeine.newBuilder()
            .expireAfterWrite(100, TimeUnit.MINUTES)
            .maximumSize(10_000)
            .build();

    /**
     * 写入缓存
     */
    public void put(String key, Object value) {
        // 添加或者更新一个缓存元素
        localCache.put(key, value);
        redisTemplate.opsForValue().set(key, value, 100, TimeUnit.MINUTES);
    }

    /**
     * 获取缓存
     */
    public Object get(String key) {
        // 先从本地缓存中获取
        Object value = localCache.getIfPresent(key);
        if (value != null) {
            return value;
        }

        // 本地缓存未命中，尝试从 redis 中获取
        value = redisTemplate.opsForValue().get(key);
        if (value != null) {
            // 将 redis 的值写入到本地缓存
            localCache.put(key, value);
        }
        return value;
    }

    /**
     * 删除缓存
     */
    public void delete(String key) {
        // 移除一个缓存元素
        localCache.invalidate(key);
        redisTemplate.delete(key);
    }

    public void deleteAll(){
        // 删除 redis 所有缓存
        /*Set<String> keys = redisTemplate.keys("*");
        if (keys != null && CollUtil.isNotEmpty(keys)){
            redisTemplate.delete(keys);
        }*/
        redisTemplate.getConnectionFactory().getConnection().flushAll();
        // 删除所有本地缓存
        System.out.println("Before clearing: " + localCache.estimatedSize());
        localCache.invalidateAll();
        System.out.println("After clearing: " + localCache.estimatedSize());
    }

}
